/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useEffect, useMemo, useState, useCallback } from 'react';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, Input, message, Popconfirm } from 'antd';
import type { StringObjType } from '@/components/_pages/AmountApply/index.d';
import { usePageTabsChange } from '@/utils/hooks/pageTabs';
import { useRangePicker } from '@/utils/hooks/rangePicker';
import { getApplicantUpdate, getStationInvoiceList } from '@/services/finance_receipt';
import type { Key } from 'antd/es/table/interface';
import styles from './index.less';
import { stationReceiptColumns } from './utils';
import type { ProFormInstance } from '@ant-design/pro-form';
import QueryString from 'qs';
import { useOperationStation } from './hooks';
import moment from 'moment';

const ReceiptTemplate: React.FC<{ activeKey: boolean }> = (props) => {
  const { activeKey } = props;
  const [show] = usePageTabsChange();
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [selectList, setSelectList] = useState<Key[]>();
  const [operationStatus, setOperationStatus] = useState<string>('0');
  const RangePicker = useRangePicker({
    valuesKeys: ['s_date', 'e_date'],
    defaultRange: 30,
    limitValueRange: 180,
  });

  const refreshList = useCallback(() => {
    setSelectList([]);
    actionRef.current?.reload();
  }, [actionRef]);

  const Operation = useOperationStation({
    width: 120,
    operationStatus,
    refreshList: refreshList,
  });

  const isShowInvoice = useMemo(() => operationStatus == '0', [operationStatus]);

  useEffect(() => {
    if (show && activeKey) {
      refreshList();
    }
  }, [show, activeKey]);

  const stationcolumns: ProColumns<StringObjType>[] | any = useMemo(
    () => [
      {
        title: '',
        hideInTable: true,
        dataIndex: 'company_type',
        valueType: 'radioButton',
        initialValue: '1',
        valueEnum: {
          '1': { text: '快宝' },
          '2': { text: '通递' },
        },
        colSize: { span: 2 },
      },
      RangePicker,
      {
        title: '发票类型',
        hideInTable: true,
        dataIndex: 'invoice_type',
        valueType: 'select',
        initialValue: '0',
        valueEnum: {
          '0': { text: '全部' },
          '1': { text: '普票' },
          '2': { text: '专票' },
        },
        fieldProps: {
          allowClear: false,
        },
      },
      {
        title: '开票状态',
        hideInTable: true,
        dataIndex: 'type',
        valueType: 'select',
        initialValue: '0',
        valueEnum: {
          '0': { text: '待开票' },
          '1': { text: '已开票' },
          '-1': { text: '已拒绝' },
        },
        fieldProps: {
          allowClear: false,
        },
      },
      {
        title: '',
        hideInTable: true,
        dataIndex: 'keyword',
        renderFormItem: () => {
          return <Input name='keyword' placeholder='输入网点编号，名称或抬头' />;
        },
      },
      ...stationReceiptColumns,
      {
        ...Operation,
        fixed: 'right',
      },
    ],
    [Operation, RangePicker],
  );

  const onFinish = async (params: StringObjType) => {
    const { code, data, msg } = await getStationInvoiceList(params);
    if (code == 0) {
      setOperationStatus(params.type);
      const { result, ...rest } = data;
      return {
        data: result,
        ...rest,
      };
    }
    if (code != 0) {
      message.error(msg);
    }
    return {};
  };

  const onDownload = () => {
    const {
      invoice_type = '',
      keyword = '',
      type = '',
      dates = [],
      company_type,
    } = formRef.current?.getFieldsValue();
    const query = QueryString.stringify({
      invoice_type,
      type,
      keyword,
      s_date: moment(dates[0]).format('YYYY-MM-DD'),
      e_date: moment(dates[1]).format('YYYY-MM-DD'),
      company_type,
    });
    window.open('/invoice/applicantsDowExcel?' + query, '_self');
  };

  return (
    <DragTable>
      <ProTable<StringObjType>
        className={`kb-pro-table ${styles.receipt}`}
        actionRef={actionRef}
        formRef={formRef}
        rowKey='id'
        request={onFinish}
        columns={stationcolumns}
        options={false}
        scroll={{ x: 1600 }}
        rowSelection={
          isShowInvoice
            ? {
                // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                // 注释该行则默认不显示下拉选项
                // selections: isShowInvoice ? [Table.SELECTION_ALL, Table.SELECTION_INVERT] : [],
                onChange: (ids) => setSelectList(ids),
                selectedRowKeys: selectList,
              }
            : false
        }
        pagination={{
          pageSize: 20,
          showSizeChanger: false,
        }}
        search={{
          collapseRender: () => <></>,
          collapsed: false,
          optionRender: (_, __, dom) => [
            ...dom.reverse(),
            <Button key='download' type='primary' style={{ marginLeft: 20 }} onClick={onDownload}>
              下载
            </Button>,
            isShowInvoice && (
              <Button key='phone' type='primary' disabled={!(selectList && selectList.length != 0)}>
                <Popconfirm
                  key='mutil'
                  title='确定批量开票？'
                  onConfirm={getApplicantUpdate.bind(null, {
                    id: selectList?.join() || '',
                    status: 1,
                    callback: refreshList,
                  })}
                >
                  批量开票
                </Popconfirm>
              </Button>
            ),
          ],
        }}
      />
    </DragTable>
  );
};

export default ReceiptTemplate;
